﻿using System;
using System.Web.Configuration;
using System.Data;
using System.Security.Cryptography;
using System.Text;
public partial class login : System.Web.UI.Page
{
    DBHelper db = new DBHelper(WebConfigurationManager.ConnectionStrings["connString"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        lblSYSName.Text = WebConfigurationManager.AppSettings["SYSName"].ToString();
        lblTitle.Text = WebConfigurationManager.AppSettings["SYSName"].ToString();
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        string strUserAccount = StringHelper.SafeSqlInput(txtUserName.Text.Trim());
        string strUserPwd = Md5Encrypt(StringHelper.SafeSqlInput(txtPassword.Text.Trim()));

        if (strUserAccount == "" || strUserPwd == "")
        {
            lblmsg.Text = "用户名或密码不能为空";
        }
        else
        {
            DataTable dtUser = db.getList("[v_user]", "id,userName,userAccount,roleID,userbh,dept,psid", "userAccount='" + strUserAccount.Trim() + "' AND userpwd='" + strUserPwd + "' AND isusing=1", "ID DESC");
            if (dtUser.Rows.Count > 0)
            {
                Session[AppConfig.SESSION_USER_ISLOGIN] = "1";
                Session[AppConfig.SESSION_USER_NAME] = dtUser.Rows[0]["userName"].ToString();
                Session[AppConfig.SESSION_USER_ACCOUNT] = dtUser.Rows[0]["userAccount"].ToString();
                Session[AppConfig.SESSION_USER_ROLE_ID] = dtUser.Rows[0]["roleID"].ToString();
                Session[AppConfig.SESSION_USER_BH] = dtUser.Rows[0]["userbh"].ToString();
                Session[AppConfig.SESSION_USER_DEPT] = dtUser.Rows[0]["dept"].ToString();
                Session[AppConfig.SESSION_USER_ID] = dtUser.Rows[0]["id"].ToString();
                Session[AppConfig.SESSION_USER_PSID] = dtUser.Rows[0]["psid"].ToString();

                if (string.IsNullOrEmpty(Request.QueryString["return"]))
                {
                    Response.Redirect("/welcome.aspx");
                }
                else
                {
                    // Response.Redirect(HttpUtility.UrlDecode(Request.QueryString["return"]));
                    Response.Redirect("/welcome.aspx");
                }
            }
            else
            {
                lblmsg.Text = "用户名或密码不正确";
            }
        }
    }
    public string Md5Encrypt(string data)
    {
        MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
        byte[] dataHashed = md5Hasher.ComputeHash(Encoding.Default.GetBytes(data));
        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < dataHashed.Length; i++)
        {
            sBuilder.Append(dataHashed[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }
}